<template>
  <div class="app-container">

    <!-- 标题区域 -->
    <div slot="header"
         class="clearfix job-tab-header">
      <span class="span-title">增删改查</span>
    </div>

    <!-- 查询区域 -->
    <div class="select-container">
      <!-- 表单区域 -->
      <el-form size="small"
               :inline="true"
               :model="dataForm"
               @keyup.enter.native="getDataList">
        <el-form-item>
          <el-input clearable
                    prefix-icon="el-icon-search"
                    ref="nameRef"
                    placeholder="请输入姓名"
                    v-model.trim="dataForm.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input clearable
                    prefix-icon="el-icon-search"
                    placeholder="请输入年龄"
                    maxlength='2'
                    v-model.trim="dataForm.age"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search"
                     :disabled="queryDisabled"
                     @click="getDataList">查询</el-button>
          <el-button type="success"
                     icon="el-icon-circle-plus-outline"
                     @click="addOrUpdate">新增</el-button>
          <el-button type="danger"
                     icon="el-icon-delete"
                     :disabled="dataListSelections.length <= 0"
                     @click="remove">批量删除</el-button>
          <el-switch v-model="removeForce"
                     inactive-text="逻辑删除"
                     active-text="物理删除"></el-switch>
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表区域 -->
    <el-table border
              stripe
              highlight-current-row
              height="460px"
              max-height="460px"
              size="small"
              ref="tableRef"
              tooltip-effect="dark"
              v-loading="loading"
              element-loading-text="数据加载中..."
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.5)"
              :row-key="getRowKey"
              :data="dataList"
              @row-click="handleRowClick"
              @select="handleSelect"
              @select-all="handleSelectAll"
              @selection-change="handleSelectionChange"
              @sort-change="handleSortChange">
      <!-- 索引列 -->
      <el-table-column align="center"
                       label="#"
                       type="index"
                       :index="indexRow"></el-table-column>
      <!-- check -->
      <el-table-column prop="id"
                       width="55"
                       align="center"
                       type="selection"></el-table-column>
      <!-- 列 -->
      <el-table-column prop="id"
                       width="60"
                       align="center"
                       label="id"></el-table-column>
      <el-table-column prop="name"
                       align="center"
                       label="姓名"></el-table-column>
      <el-table-column prop="sex"
                       width="100"
                       align="center"
                       sortable="custom"
                       label="性别"
                       :formatter="dataFormat"></el-table-column>
      <el-table-column prop="age"
                       width="100"
                       align="center"
                       sortable="custom"
                       label="年龄"></el-table-column>
      <el-table-column prop="email"
                       width="220"
                       align="center"
                       label="E-mail"></el-table-column>
      <el-table-column prop="createTime"
                       width="160"
                       align="center"
                       label="创建日期"></el-table-column>
      <!-- 操作 -->
      <el-table-column header-align="center"
                       label="操作"
                       width="140px">
        <template slot-scope="scope">
          <el-tooltip content="编辑"
                      placement="top"
                      :enterable="false">
            <el-button size="mini"
                       type="primary"
                       icon="el-icon-edit"
                       @click.stop="addOrUpdate(scope.row.id)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除"
                      placement="top"
                      :enterable="false">
            <el-button size="mini"
                       type="danger"
                       icon="el-icon-delete"
                       @click.stop="remove(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination :disabled="dataList.length <= 0"
                   :current-page="currPage"
                   :page-sizes="this.$store.getters.page.pageSizes"
                   :page-size="pageSize"
                   :total="total"
                   :layout="this.$store.getters.page.layout"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange">
    </el-pagination>

    <!-- Dialog(新增/修改) -->
    <add-or-update ref="addOrUpdate"
                   v-if="addOrUpdateVisible"
                   @refreshDataList="refreshDataList"></add-or-update>

  </div>
</template>

<script>
import { buildQueryCondition } from '@/utils'
import { selectList, remove } from '@/api/busiDemo/jbdpDemoCrud'
import AddOrUpdate from './jbdpdemocrud-add-or-update'
export default {
  name: 'jbdpDemoCrud',
  data() {
    return {
      busiTypeId: 'jbdpDemoCrud',
      // 查询参数
      dataForm: {
        name: '',
	/**
         * xxx_criteria 与属性相对应，处理在查询时自动为该字段匹配相应的查询方式：
         * EQ(=),NE(!=),GT(>),GE(>=),LT(<),LE(<=),LIKE,BETWEEN
         * 如果不配置该项则自动默认为 EQ 模式
         * 具体逻辑查看 buildQueryCondition()
         */
        name_criteria: 'LIKE',
        age: ''
      },
      queryArgs: {
        condition: [],
        rowBounds: {
          offset: 0,
          limit: this.$store.getters.page.pageSize
        },
        sort: [{
          property: 'id',
          direction: 'DESC'
        }]
      },
      dataList: [],
      currPage: 1,
      pageSize: this.$store.getters.page.pageSize,
      total: 0,
      loading: false,
      dataListSelections: [],
      // 防止相同条件下进行多次查询请求
      queryDisabled: true,
      removeForce: false,
      addOrUpdateVisible: false
    }
  },
  components: { AddOrUpdate },
  created() {
    this.refreshDataList()
  },
  watch: {
    'dataForm.name'(newVal, oldVal) {
      // 查询条件发生变化允许再次查询
      // console.log('watch:', newVal, oldVal);
      this.currPage = 1
      this.queryDisabled = false
    },
    'dataForm.age'(newVal, oldVal) {
      this.currPage = 1
      this.queryDisabled = false
    }
  },
  methods: {
    //
    refreshDataList() {
      this.dataForm.name = ''
      this.dataForm.age = ''
      this.queryDisabled = false
      this.getDataList()
      this.$nextTick(() => {
        this.$refs.nameRef.focus()
      })
    },
    // 获取数据列表
    async getDataList() {
      // 防止相同条件下进行多次查询请求
      if (this.queryDisabled) { return }
      this.loading = true
      // 封装查询+分页条件
      this.queryArgs.condition = buildQueryCondition(this.dataForm)
      this.queryArgs.rowBounds = {
        offset: (this.currPage - 1) * this.pageSize,
        limit: this.pageSize
      }
      // 请求后台
      const res = await selectList(this.queryArgs)
      console.log('getDataList:', res)
      if (res.data.success) {
        this.dataList = res.data.data.records || []
        this.total = res.data.data.count
      } else {
        return this.$message.error(res.data.message)
      }
      this.loading = false
      // 查询过后禁用按钮，当查询条件发生变化时再开启
      this.queryDisabled = true
    },
    getRowKey(row) {
      return row.id
    },
    // 按照数据的条数来标记索引列的序号
    indexRow(index) {
      // 第二页以后索引的序号为：(当前页-1) * 每页条数 + (当前索引+1)
      if (this.currPage > 1) {
        return (this.currPage - 1) * this.pageSize + index + 1
      }
      // 当前是第一页则索引全部+1 (index 第一条默认从 0 开始)
      return index + 1
    },
    // 点击行
    handleRowClick(row, column, event) {
      // console.log('RowClick：', row.id, row.name)
      // 用于多选表格，切换某一行的选中状态，如果使用了selected参数，则是设置这一行选中与否(selected 为 true 则选中)
      this.$refs.tableRef.toggleRowSelection(row)
    },
    // 单选 Checkbox (selection:所有已选中的项、row:当前勾选/取消的项)
    handleSelect(selection, row) {
      // console.log('Select:', row.id, row.name)
    },
    // 全选
    handleSelectAll(selection) {
      // console.log('SelectAll:', selection)
    },
    // 当选择项发生变化时触发(selection 是个数组包含当前所有选择的元素)
    handleSelectionChange(selection) {
      // console.log('SelectionChange:', selection)
      this.dataListSelections = selection
    },
    // 每页显示多少条改变时触发
    handleSizeChange(val) {
      console.log(`每页显示 ${val} 条`)
      this.currPage = 1
      this.pageSize = val
      this.queryDisabled = false
      this.getDataList()
    },
    // 当前页改变时触发
    handleCurrentChange(val) {
      console.log(`当前第 ${val} 页`)
      this.currPage = val
      this.queryDisabled = false
      this.getDataList()
    },
    // 排序变化时触发
    handleSortChange(column, prop, order) {
      // console.log('handleSortChange', column)
      if (column.prop) {
        this.queryArgs.sort = [{
          property: column.prop,
          direction: column.order === 'descending' ? 'DESC' : 'ASC'
        }]
      } else {
        this.queryArgs.sort = [{
          property: 'id',
          direction: 'DESC'
        }]
      }
      this.queryDisabled = false
      this.getDataList()
    },
    // 格式化日期列
    dataFormat(row, column, cellValue, index) {
      if (column.property === 'sex') {
        return cellValue ? '男' : '女'
      }
    },
    // 新增/修改
    addOrUpdate(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        // 调用子组件的 init 方法
        this.$refs.addOrUpdate.init(id)
      })
    },
    remove(row) {
      let ids, names
      if (row.id) {
        ids = [{ id: row.id }]
        names = row.name
      } else {
        ids = this.dataListSelections.map(item => { return { id: item.id } })
        names = this.dataListSelections.map(item => item.name).join(',')
      }
      this.$confirm(`确定要${!row.id ? '批量' : ''}删除 [${names}] 操作?`, '提示', {
        type: 'warning',
        showClose: false,
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        // console.log('remove:', this.removeForce, ids)
        let res = await remove(ids, this.removeForce)
        console.log('remove:', res)
        if (!res.data.success) { return this.$message.error('删除失败') }
        this.$message.success('删除成功')
        // 重新加载数据
        this.queryDisabled = false
        this.getDataList()
      }).catch(error => error)
    }
  }
}
</script>

<style scoped>
.select-container {
  padding: 10px 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  border: 1px solid #f1d8d8;
}
.el-form-item {
  margin-bottom: 0;
}
.el-pagination {
  margin-top: 10px;
}
</style>
